// 发布提交页
import React, { useState } from "react"
import { useNavigate, useLocation } from "react-router-dom"
import { zzy_postShoop } from '../request/api'
import { QuestionO, Success, Edit, Points, Exchange, Arrow, ArrowUp, WarningO,InfoO } from "@react-vant/icons"
import { Popup, Form, Input, Picker, Switch, Uploader, Tag, SubmitBar, Toast, Notify, NoticeBar } from "react-vant"
import { useSelector } from 'react-redux'
import instance from '../request/instance'
import styles from './fBSubmit.module.css'
import { NavBar } from 'antd-mobile'

export default function FBSubmit() {
    let uploadApi = instance.defaults.baseURL
    const location = useLocation()
    const [visible, setVisible] = useState(true)
    const user = useSelector(store => store.user.userInformation)
    const [taglist, setTaglist] = useState([])
    const navigate = useNavigate()
    const obj = location.state
    //创建表单实例
    const [form] = Form.useForm()
    //监听表单字段
    const loginMethod = Form.useWatch('loginMethod', form)
    const price = Form.useWatch('price', form)
    //上传图片
    const upload = async (file) => {
        const body = new FormData()
        body.append('source', file)
        const resp = await fetch(uploadApi + 'release/upload', {
            method: 'POST',
            body,
        })
        const json = await resp.json()
        if (json.url) {
            form.setFieldValue('imgSrc', json.url)
        }
        return json
    }
    //根据表单字段获取保证金
    const getCommission = (price) => {
        if (price <= 100) {
            return price * 0.03;
        } else if (price <= 500) {
            return price * 0.06;
        } else if (price <= 1000) {
            return price * 0.1;
        } else {
            return price * 0.15;
        }
    };
    const commission = getCommission(price)

    //表单提交
    const onFinish = async (values) => {
        console.log(values);

        values.label = taglist
        values.userId = user.arr?._id
        if (!values.userId) {
            navigate('/login')
            Toast.fail('发布商品前请先登录')
            return
        }
        values.shoopType = obj.shoopType
        values.typeId = obj.typeId
        values.imgSrc = values.imgSrc.map(item => item.url)
        let res = await zzy_postShoop(values)
        if (res.data.code == 200) {
            navigate('/myRelease/pron')
            Toast.success('发布成功')
        }
    }
    //删除标签
    const handleClose = (item) => {
        let newlist = taglist.filter(i => i !== item)
        setTaglist(newlist)
    }
    //添加标签
    const handleAddTag = (e) => {
        const value = e.target.value
        setTaglist(pre => {
            if (!Array.isArray(pre)) {
                pre = []
            }
            if (value.trim() != '') {
                if (pre.includes(value.trim())) {
                    return pre
                } else {
                    if (pre.length >= 5) {
                        return pre
                    } else {
                        return [...pre, value.trim()]
                    }

                }
            }
        })
        form.setFieldValue('label', '')
    }

    return <>
    <div className={styles.main}>
    <Popup
            round
            visible={visible}
            position='top'
            onClose={() => setVisible(false)}>
            <div>
                <h2>官方托管</h2>
                <p><Success color="orange" />官方交易员帮你上号截图，采集信息</p>
                <p><Success color="orange" />买家下单后无需验号，官方交易员协助换绑</p>
                <h4>交易流程</h4>
                <div className={styles.box2}>
                    <div >
                        <Edit color="orange" />
                        <p>官方上号采集</p>
                    </div>
                    <Arrow color="gray" />
                    <div >
                        <Points color="orange" />
                        <p>买家付款</p>
                    </div>
                    <Arrow color="gray" />
                    <div >
                        <Exchange color="orange" />
                        <p>官方协助换绑</p>
                    </div>
                    <Arrow color="gray" />
                    <div >
                        <Success color="orange" />
                        <p>坐等收款</p>
                    </div>
                </div>
            </div>
            <div className={styles.box} onClick={() => setVisible(false)}>点击收起<ArrowUp /> </div>
        </Popup >
        <div>
        <NavBar
            right={
                <span onClick={() => navigate(-1)}>取消</span>
            }
            backIcon={false}
            onClickRight={() => navigate(-1)}>
            <div>
                <div >商品发布-官方托管<QuestionO onClick={() => setVisible(true)} /></div>
                <div className={styles.ftitle}>{obj.name}-{obj.shoopType}出售-多端发布</div>
            </div>
        </NavBar>
        </div>
       <div>
       <NoticeBar wrapable text={
            <>
                <WarningO color='red' /> 信息仅用于官方交易员协助买家验号换绑。密码全程加密处理，确保信息安全。
                虚拟财产严禁平台线下交易,谨防诈骗。"
            </>} background='linear-gradient(to right, green, blue)'
        />
       </div>
        <div>
        <Form form={form}
        layout="vertical"
            onFinish={onFinish}>
            <Form.Item
                rules={[{ required: true, message: '请填写商品标题' }]}
                name='title'
                label='商品标题'
            >
                <Input placeholder='请输入商品标题' />
            </Form.Item>
            <Form.Item name='loginMethod' label='登录方式' isLink trigger='onConfirm' rules={[{ required: true, message: '请选择登录方式' }]}
                onClick={(_, action) => {
                    action.current?.open()
                }}>
                <Picker
                    popup
                    columns={[
                        'QQ',
                        '微信',
                        '手机号'
                    ]}
                >
                    {val => val || '请选择登录方式'}
                </Picker>
            </Form.Item>
            <Form.Item name='operatingSystem' label='操作系统' isLink trigger='onConfirm' rules={[{ required: true, message: '请选择操作系统' }]}
                onClick={(_, action) => {
                    action.current?.open()
                }}>
                <Picker
                    popup
                    columns={[
                        '安卓',
                        '苹果',
                        '鸿蒙'
                    ]}
                >
                    {val => val || '请选择操作系统'}
                </Picker>
            </Form.Item>
            <Form.Item
                intro='帐号交易需把手机号码告知买家'
                initialValue={''}
                rules={[
                    { required: loginMethod == '手机号', message: '请填写手机号' },
                    { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: '手机号格式不对' }
                ]}
                name='phone'
                label='手机号'
            >
                <Input placeholder='请输入手机号' />
            </Form.Item>
            <Form.Item
                intro='填写时请保证账号正确'
                rules={[{ required: loginMethod != '手机号', message: '请填写游戏账号' }]}
                initialValue={''}
                name='userName'
                label='账号'
            >
                <Input placeholder='请输入用户名' />
            </Form.Item>
            <Form.Item
                intro='温馨提示:帐号密码正确的商品，可大幅缩短售出时间'
                initialValue={''}
                rules={[{ required: true, message: '请填写密码' }]}
                name='passWord'
                label='密码'
            >
                <Input type="password" placeholder='请输入密码' />
            </Form.Item>

            <Form.Item name='isChangeId' label='是否能换绑' valuePropName='checked' initialValue={false}>
                <Switch size={20} inactiveColor='red' />
            </Form.Item>
            <Form.Item name='label' label='商品标签' intro={
                <>
                    {taglist && taglist.length > 0 ?
                        <div className={styles.tag}>
                            {taglist.map(item => (
                                <Tag key={item} closeable plain color="orange" onClose={() => handleClose(item)}>{item}</Tag>
                            ))}
                        </div> : '标签最多输入5个,最大长度不超过5,按Enter添加标签'
                    }
                </>
            } >
                <Input placeholder='请输入商品标签' maxLength={5}
                    onKeyDown={(e) => {
                        if (e.key == 'Enter') {
                            handleAddTag(e)
                        }
                    }} />
            </Form.Item>
            <Form.Item name='imgSrc' label='商品截图' initialValue={[]}>
                <Uploader upload={upload} />
            </Form.Item>
            <Form.Item name='price' label='出售价格' rules={[{ required: true, message: '请输入售价' }]}>
                <Input placeholder='请输入出售价格' />
            </Form.Item>
        </Form>
        </div>
        <div className={styles.jg}></div>
        </div>
        <div className={styles.bar}><SubmitBar label='预估收益' price={price ? (price - commission) * 100 : 0} 
         tipIcon={<InfoO />}
        tip={
            <>
                为了防止恶意交易,交易完成后会抽取部分金额作为保证金，本次抽取保证金：{commission ? commission.toFixed(2) : 0}  元。
                具体规则请查看<span className={styles.gz} onClick={() => Notify.show({ type: 'success', message: '交易额100以下收取3%;500以下收取6%;1000以下收取10%,以上收取15%' })}>《具体规则》</span>
            </>
        } buttonText="提交订单" onSubmit={() => form.submit()} /></div>
    </>
}